package com.example.up;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import com.alibaba.fastjson.JSON;
import com.example.up.enty.Version;
import com.example.up.util.Content;
import com.example.up.util.HttpUtil;
import com.example.up.util.LogsReaderWriter;
import com.example.up.util.UpdateManager;
import com.example.up.view.CustomProgressDialog;

import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private String url = "http://media.vzume.com/checkMocoVersion";
	private TextView level = null;
	private Button confirm = null;
	public static String mcu_verson = "";
	private int batter_percent = 0;
	Version vr = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.update_msg_activity);

		Intent intent = this.getIntent();

		mcu_verson = intent.getStringExtra("mcu_version");
		batter_percent = intent.getIntExtra("batter_percent", 0);

		
		if (intent != null) {
			// Toast.makeText(MainActivity.this,mcu_verson+"1  "+batter_percent, Toast.LENGTH_LONG).show();
		}
		ImageView img = (ImageView) findViewById(R.id.id_back);
		img.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				HttpUtil.start(MainActivity.this);
				Content.sendStopBoradcast(MainActivity.this, "");
			}
		});

		level = (TextView) findViewById(R.id.level_txt);
		confirm = (Button) findViewById(R.id.confirm);

		if (isOpenNetwork()) {
			AnsyHttp http = new AnsyHttp(MainActivity.this);
			http.execute(url);
		} else {
			Toast.makeText(MainActivity.this, "网络未连接", Toast.LENGTH_LONG)
					.show();
			TimerTask task = new TimerTask() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					HttpUtil.start(MainActivity.this);
				}
			};
			Timer time = new Timer();
			time.schedule(task, 1000);

		}

	}

	private class AnsyHttp extends AsyncTask<String, Integer, String> {

		CustomProgressDialog pdialog;

		public AnsyHttp(Context context) {
			pdialog = CustomProgressDialog.createDialog(MainActivity.this);
			pdialog.setMessage("正在加载数据...");
			pdialog.setCancelable(true);
			pdialog.show();
		}

		protected String doInBackground(String... arg0) {
			
				Map<String, String> map = new HashMap<String, String>();
				map.put("systemVersion", getDragonVersion());
				map.put("appVersion", String.valueOf(getVersionCode()));
				 
				if(mcu_verson==null)
			    	map.put("mcuVersion", "");
				else
					map.put("mcuVersion", mcu_verson);
		    	String  result= HttpUtil.sendPost(url, map);
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			// Toast.makeText(MainActivity.this, result,
			// Toast.LENGTH_LONG).show();

			pdialog.dismiss();
			if (result.length() == 0) {
				// Toast.makeText(MainActivity.this, "未能有效的获取服务器的数据",
				// Toast.LENGTH_LONG).show();
				level.setText("未能获取有效的数据");
				confirm.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						HttpUtil.start(MainActivity.this);
					}

				});
			} else {

				vr = JSON.parseObject(result, Version.class);

				if (vr.isNeedUpgrade()) {
					if (vr.getUpgradeType().equals("app")) {
						level.setText(MainActivity.this
								.getString(R.string.l_app)
								+ vr.getVersionNumber());
						// UpdateManager.getInstance(MainActivity.this).checkUpdate(vr.getVersionNumber(),
						// vr.getUpgradeUrl());
					} else if (vr.getUpgradeType().equals("system")) {
						level.setText(MainActivity.this
								.getString(R.string.l_sys)
								+ vr.getVersionNumber());
						// UpdateManager.getInstance(MainActivity.this).checkUpdateota(vr.getVersionNumber(),
						// vr.getUpgradeUrl(),vr.getMd5());

					} else if (vr.getUpgradeType().equals("mcu")) {
						level.setText(MainActivity.this
								.getString(R.string.l_mcu)
								+ vr.getVersionNumber().trim()
										.replace(" ", "-"));
					}

				} else {
					level.setText(MainActivity.this.getString(R.string.l_no));

				}

				confirm.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View arg0) {

						if (!vr.isNeedUpgrade()) {
							HttpUtil.start(MainActivity.this);
						} else {

							if (vr.getUpgradeType().equals("app")) {

								UpdateManager.getInstance(MainActivity.this).checkUpdate(vr.getVersionNumber(),vr.getUpgradeUrl());
							} else if (vr.getUpgradeType().equals("system")) {
						
								UpdateManager.getInstance(MainActivity.this).checkUpdateota(vr.getVersionNumber(),vr.getUpgradeUrl(), vr.getMd5(),batter_percent);
							} else if (vr.getUpgradeType().equals("mcu")) {
							
								UpdateManager.getInstance(MainActivity.this).checkUpdateMcu(mcu_verson,vr.getVersionNumber().trim(),vr.getUpgradeUrl(),batter_percent);

							}
						}
					}

				});

			}

			super.onPostExecute(result);
		}
	}

	/**
	 * 获取软件版本号
	 * 
	 * @param context
	 * @return
	 */
	private int getVersionCode() {
		int versionCode = 0;
		try {
			// 获取软件版本号，对应AndroidManifest.xml下android:versionCode
			versionCode = this.getPackageManager().getPackageInfo(
					Content.packger, 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * 获取固件
	 * 
	 * @return
	 */
	public String getDragonVersion() {
		String str1 = "/system/build.prop";
		return LogsReaderWriter.readFromFile(str1, "ro.product.firmware")
				.substring(20).substring(0, 7);

	}

	/**
	 * 对网络连接状态进行判断
	 * 
	 * @return true, 可用； false， 不可用
	 */
	private boolean isOpenNetwork() {
		ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connManager.getActiveNetworkInfo() != null) {
			return connManager.getActiveNetworkInfo().isAvailable();
		}

		return false;
	}
}
